<?php

/*
 * Plugin Name: SaleSea
 * Plugin URI: https://www.salesea.cn
 * Description: SALESEA文章自动发布插件
 * Version: 1.0
 * Author: SaleSea
 * Author URI: https://www.salesea.cn
 * License: GPL2
 * Text Domain: salesea
 */
defined('ABSPATH') OR exit('No direct script access allowed');
$path = preg_replace( '/wp-content(?!.*wp-content).*/', '', __DIR__ );
define('WP_ROOT', $path);
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/tasks.php';
require_once __DIR__.'/functions.php';
require_once __DIR__."/input.php";
require_once __DIR__.'/include.php';

//load text domain when the plugin is loaded
add_action('plugins_loaded', 'salesea_load_textdomain');
function salesea_load_textdomain(){
	load_textdomain('salesea', false, basename( dirname( __FILE__ ) ) . '/languages');
}

//create task table while activating the plugin
register_activation_hook( __FILE__, 'activate_salesea_tasks_table');
function activate_salesea_tasks_table()
{
	global $wpdb;
	$table_name = $wpdb->prefix . 'salesea_tasks';
	$sql = "CREATE TABLE $table_name (
         id mediumint(9) NOT NULL AUTO_INCREMENT, 
         keyword varchar(150) NOT NULL,
         title varchar(255) NOT NULL,
         related varchar(255) NOT NULL DEFAULT '',
         prompt text NOT NULL,
         taskid varchar(255) NOT NULL,
         status tinyint(1) NOT NULL DEFAULT 0,
         cat_id smallint(5) NOT NULL DEFAULT 0,
         img varchar(255) NOT NULL DEFAULT '',
         created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
         PRIMARY KEY (id)
     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";

    if(!is_dir(__DIR__."/output/")){
		mkdir(__DIR__."/output/");
    }
	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql );
}

register_deactivation_hook( __FILE__, 'deactivate_salesea_tasks_table');
function deactivate_salesea_tasks_table(){
    $timestamp = wp_next_scheduled( 'salesea_cron_hook' );
	wp_unschedule_event( $timestamp, 'salesea_cron_hook' );
	$qingchu = _wenda("qingchushuju");
	if($qingchu){
			global $wpdb;
	        $table_name = $wpdb->prefix . 'salesea_tasks';
	        $sql = "DROP TABLE $table_name";
	        $wpdb->query( $sql );
			delete_option('wenda');
	}
}

function salesea_disable_cron_on_save()
{
	global $wpdb;
	$wenda = get_option('wenda');
	$table_name = $wpdb->prefix . 'options';

	if($wenda["renwuzhuangtai"]){
		$sql = "DELETE FROM $table_name WHERE option_name = 'cron'";
		$wpdb->query($sql);
	}else{
		$sql = "UPDATE $table_name SET option_value = '' WHERE option_name = 'cron'";
		$wpdb->query($sql);
	}
}

add_action('csf_salesea_saved', 'salesea_disable_cron_on_save');

 function salesea_return_random_keyword()
 {
	$salesea_key_fields = salesea_get_category_list_and_return_fields();
	foreach($salesea_key_fields as $salesea_key){
		$key_array[] = $salesea_key['id'];
	}
	shuffle($key_array);
	$categories = get_categories(['hide_empty' => false]);
	foreach($categories as $category){
		$cat_array[] = $category->cat_ID;
	}
	shuffle($cat_array);
	foreach ($key_array as $key){
		if ($key  === 'suijifenlei'){
			$cat_id = $cat_array[0];
			$keywords = _wenda('suijifenlei');
			if(empty($keywords)){
				continue;
			}
			$keywords_array = explode(PHP_EOL, $keywords);
			$keywords_array = array_unique($keywords_array);
			$random_index = array_rand($keywords_array);
			//随机挑选一个关键词
			$random_picked_keyword = $keywords_array[$random_index];
			$salesea_key_index = "suijifenlei";
            break;
		}else{
			$cat_id = substr($key, 12);
			$keywords = _wenda('keywords_cat'.$cat_id);
			if(empty($keywords)){
				continue;
			}
			$keywords_array = explode(PHP_EOL, $keywords);
			$keywords_array = array_unique($keywords_array);
			$random_index = array_rand($keywords_array);
			$random_picked_keyword = $keywords_array[$random_index];
			$salesea_key_index = "keywords_cat".$cat_id;
			break;
		}
	}

	return ['keyword' => $random_picked_keyword, 'cat_id' => $cat_id, 'salesea_key_index' => $salesea_key_index, "keywords_array" => $keywords_array];
 }

 function salesea_handle()
 {
	 $random_keyword = salesea_return_random_keyword();
	 $keyword = $random_keyword['keyword'];
	 $cat_id = $random_keyword['cat_id'];
	 $salesea_key = $random_keyword['salesea_key_index'];
	 if($keyword){
		 $titles = salesea_generate_title($keyword);
		 $title = ucwords($titles["title"]);
		 $related = $titles['related'];
		 salesea_save_taskid_and_title_into_task($title, $keyword, $cat_id, $related);
		 $result = salesea_insert_task_queue_or_insert_post();
		 if(isset($result['inserted']) && $result['inserted'] != 0){
			 if($salesea_key === "suijifenlei"){
				 remove_salesea_keyword_and_update($result['keyword'], "suijifenlei");
			 }else{
				 remove_salesea_keyword_and_update($result['keyword'], $salesea_key);
			 }
		 }
	 }
 }

//add a custom wordpress api endpoint
add_action( 'rest_api_init', function () {
	register_rest_route( 'salesea', '/generate(?:/(?P<key>[^/]+))?', array(
		'methods'  => 'GET', // or 'POST', 'PUT', etc.
		'callback' => 'salesea_task_execute',
		'permission_callback' => '__return_true'
	));
});

function salesea_task_execute(WP_REST_Request $request){
    $key = $request['key'];
	$wenda = get_option('wenda');
	$article_key = $wenda['article-key'];
	if(!empty($article_key)){
		if($key === $article_key){
			salesea_handle();
			salesea_insert_generated_thumbnail();
			return ["msg" => "success"];
		}
	}else{
		salesea_handle();
		salesea_insert_generated_thumbnail();
		return ["msg" => "success"];
	}
}
